package com.putiman.server;

import com.putiman.protocol.RequestProtocol;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * rpc服务端
 * 核心实现步骤：
 * 1、暴露调用服务接口
 * 2、启动服务端
 */
public class RPCServer {
    //定义存储暴露服务列表
    Map<String, Object> serverMap = new ConcurrentHashMap<>(32);

    //定义一个线程池
    ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(8, 20, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));

    /**
     * 暴露服务的方法
     *
     * @param interfaceClass
     * @param instance
     */
    public void publishServiceAPI(Class<?> interfaceClass, Object instance) {
        this.serverMap.put(interfaceClass.getName(), instance);
    }

    /**
     * 定义启动服务的方法
     *
     * @param port
     */
    public void start(int port) {
        //创建网络服务端
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("rpc server started...");
            while (true) {
                poolExecutor.execute(new ServerTask(serverSocket.accept()));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建客户端请求处理的线程类
     */
    private class ServerTask implements Runnable {
        private Socket socket;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (
                    ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                    ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ) {
                //反序列化获取客户端传入的数据
                RequestProtocol requestProtocol = (RequestProtocol) inputStream.readObject();
                //获取接口全名称
                String interfaceClassName = requestProtocol.getInterfaceClassName();
                Object instance = serverMap.get(interfaceClassName);
                if (null == instance) {
                    return;
                }
                //创建一个方法对象
                Method method = instance.getClass().getDeclaredMethod(requestProtocol.getMethodName(), requestProtocol.getParameterTypes());
                Object result = method.invoke(instance, requestProtocol.getParameterValues());
                //序列化调用的结果
                outputStream.writeObject(result);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
